package com.alibaba.nacos.naming.push.v2.task;

import com.alibaba.nacos.common.task.AbstractDelayTask;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

/**
 * using by {@link PushDelayTaskExecuteEngine.PushDelayTaskProcessor}
 */
@AllArgsConstructor
@Getter
@Setter
public class PushDelayTask extends AbstractDelayTask {

    private final Service service;
    private boolean pushToAll;
    private Set<String> targetClients;

    public PushDelayTask(Service service, long delay) {
        this(service, true, null);
        setTaskInterval(delay);
    }

    public PushDelayTask(Service service, long delay, String targetClient) {
        this(service, false, new HashSet<>());
        this.targetClients.add(targetClient);
        setTaskInterval(delay);
    }

    @Override
    public void merge(AbstractDelayTask task) {
        if (task instanceof PushDelayTask oldTask) {
            if (isPushToAll() || oldTask.isPushToAll()) {
                pushToAll = true;
                targetClients = null;
            } else {
                targetClients.addAll(oldTask.getTargetClients());
            }

            setLastProcessTime(Math.min(getLastProcessTime(), oldTask.getLastProcessTime()));
        }
    }
}
